package format

import (
	"encoding/json"
	"fmt"
	"geekai/api/dto/response"
	"geekai/core/store"
	"geekai/core/types"
	"github.com/go-redis/redis/v8"
	"net/url"
	"time"
)

type WeiBoFormatService struct {
	Url       string
	RedisHash *store.RedisHash
}

func NewWeiBoFormatService(redisCli *redis.Client) *WeiBoFormatService {
	return &WeiBoFormatService{
		Url:       types.WEI_BO,
		RedisHash: store.NewRedisHash(types.HOT_SEARCH_KEY, redisCli),
	}
}

func (s *WeiBoFormatService) Format(body []byte) {
	resp := response.WeiBoHotResponse{}
	err := json.Unmarshal(body, &resp)
	if err != nil {
		log.Errorf("解析 JSON 失败：%v\n", err)
	}
	var formattedSlice []response.WeiBoFormattedTopic
	for _, topic := range resp.Data.Realtime {
		// 过滤广告
		if topic.IsAd == 1 {
			continue
		}
		formattedTopic := response.WeiBoFormattedTopic{
			ID:    topic.Word,
			Title: topic.Word,
		}
		// 设置关键词
		keyword := topic.WordScheme
		if keyword == "" {
			keyword = fmt.Sprintf("#%s#", topic.Word)
		}
		// 设置图标
		if topic.Icon != "" {
			formattedTopic.Extra.Icon.URL = topic.Icon
		}
		// 编码关键词
		encodedKeyword := url.QueryEscape(keyword)
		// 设置访问链接
		formattedTopic.URL = fmt.Sprintf(types.WEI_BO_VISIT_URL, encodedKeyword)
		formattedTopic.MobileURL = fmt.Sprintf(types.WEI_BO_VISIT_MOBILE_URL, encodedKeyword)
		formattedSlice = append(formattedSlice, formattedTopic)
	}
	formattedSlice = formattedSlice[:5]
	encodeData, err := json.Marshal(formattedSlice)
	if err != nil {
		log.Errorf("json编码出现错误：%v\n", err)
		return
	}
	// 保存热搜数据
	weiBoCacheMap := map[string]interface{}{
		types.WEIBO_HOT_SEARCH_FIELD:       string(encodeData),
		types.HOT_SEARCH_UPDATE_TIME_FIELD: time.Now().UnixMilli(),
	}
	s.RedisHash.HSet(weiBoCacheMap)
}
